import Vue from 'vue'
import VueRouter from 'vue-router'
import Article from '@/views/article'
import Dashboard from '@/views/dashboard'
import Layout from '@/views/layout'
import Login from '@/views/login'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard },
      { path: 'article', component: Article }
    ]
  }
]
// 解决vue-router 报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})

// to:表示去哪儿
// from: 表示从哪儿来
// next() 表示放行 next('/路径') 重新跳转到这个路径
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // 从vuex中取token
  const token = store.state.user.token
  if (token) {
    // 表示有token
    if (whiteList.includes(to.path)) {
      // 有token 访问登录 跳转到首页
      next('/')
    } else {
      // 有token 访问的其他页  直接放行
      next()
    }
  } else {
    // 没token
    if (whiteList.includes(to.path)) {
      // 没token 访问的是白名单 放行
      next()
    } else {
      // 没token 访问的其他页面 跳转到登录
      next('/login')
    }
  }
  next()
})
export default router
